package cn.getword.cnblogs.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class DBUtils {
	/**
	 * 获取数据库方言
	 * @return
	 * @throws IOException 
	 */
	public static String getDialect() throws Exception {
		String dialect = "mysql";
		InputStream stream = DBUtils.class.getResourceAsStream("/mybatis/mybatis-config.xml");
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(stream);
		Element rootElement = document.getRootElement();
		Element element = (Element) rootElement.selectSingleNode("properties/property[@name='dialect']");
		if (element != null) {
			dialect = element.attributeValue("value");
		}
		return dialect;
	}

	public static Connection getConnection() throws Exception {
		Connection conn = null;
		InputStream stream = DBUtils.class.getResourceAsStream("/application.properties");
		Properties props = new Properties();
		props.load(stream);
		Class.forName(props.getProperty("spring.datasource.driverClassName"));
		Properties params = new Properties();
		params.put("remarksReporting", "true");
		params.put("user", props.get("spring.datasource.username"));
		params.put("password", props.get("spring.datasource.password"));
		conn = DriverManager.getConnection(props.get("spring.datasource.url") + "", params);
		return conn;
	}
}